/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.gjt.mm.mysql.Driver;

/**
 *
 * @author Master
 */
public class DataProvider {
    private Connection connection;
    
    public void Open(){
        try {
            Driver d = new Driver();
            String url = "jdbc:mysql://localhost/congtyduongsat";
            DriverManager.registerDriver(d);
            Properties p = new Properties();
            
            p.setProperty("characterEncoding", "utf8");
            p.setProperty("user", "root");
            p.setProperty("password", "");
            
            this.connection = DriverManager.getConnection(url, p);
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }
    
    public void Close(){
        try {
            this.connection.close();
        } catch (SQLException e) {
            System.err.printf(e.getMessage());
        }
    }
    
    public ResultSet ExecuteQuery(String sql){
       ResultSet rs = null;
       
        try {
            java.sql.Statement sm = this.connection.createStatement();
            rs = sm.executeQuery(sql);
        } catch (SQLException e) {
            System.err.printf(e.getMessage());
        }
        
        return rs;
    }
    
    public int ExeCuteUpdate(String sql){
        int n = -1;
        
        try {
            java.sql.Statement sm = this.connection.createStatement();
            n = sm.executeUpdate(sql);
        } catch (SQLException e) {
            System.err.printf(e.getMessage());
        }
        
        return n;
    }
    
    public String MD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
